<html>
<head>
<title>problem</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js" type="text/javascript"></script>
</head>
<body>

<div>
    I want to replace in
    <script type="text/javascript">
    document.write("the middle");
    </script>    
    of a node
    <script type="text/javascript">
    document.write(" and, besides to replace inside dynamically generated content ");
    </script>

    <p>
        P.S. Checking if 3-rd party API is working. Here Twitter's follow button of Warface.com is supposed to be displayed: 
    
        <a href="https://twitter.com/share" class="twitter-share-button" data-url="http://www.warface.com/" data-via="WarfaceGame" data-lang="en"><!-- --></a>
        <script type="text/javascript">
        !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
        </script>
    </p>
</div>

<script type="text/javascript">
// let's take it out of the global scope
(function() {
    $(document).ready(function() {
        var boundingBox = $('body > div'),
        replaceHandler = function(idx, oldhtml) {
            return oldhtml.replace(/replace/g, '<a href="">replace</a>' );
        };
        boundingBox.find('script').detach();
        boundingBox.html(replaceHandler);        
    });
})();
</script>
</body>
</html>
